<?php

namespace models;

use Unirest\Request;

class Basket {
		
	/** 根据sourceId, openid, type 获取菜篮子 **/
	public static function getByUidTypeSid($db, $userId, $type, $sourceId) {
        $sql = "SELECT * FROM t_basket WHERE userId = ? AND type = ? AND sourceId = ? AND isDeleted=false";
	    $data = $db->fetchAll($sql, array($userId, $type, $sourceId));
	    return $data;
    }

    /** 加入菜篮子 **/
	public static function add($db, $userId, $type, $sourceId, $name, $extra) {
        $sql = "INSERT INTO t_basket(userId, type, sourceId, name, extra, isChecked, createdAt, modifiedAt, isDeleted) VALUES(?,?,?,?,?,?,?,?,?)";
	    $data = $db->executeUpdate($sql, array($userId, $type, $sourceId, $name, $extra, false, time(), time(), false));
	    return $data;
    }

    /** 从菜篮子移除 **/
	public static function remove($db, $userId, $type, $sourceId) {
		$time = time();
        $sql = "DELETE FROM t_basket WHERE userId = ? AND type = ? AND sourceId = ?";
	    $data = $db->executeUpdate($sql, array($userId, $type, $sourceId));
	    return $data;
    }

    /** 我的菜篮 **/
	public static function getByUid($db, $userId) {
		$time = time();
        $sql = "SELECT * FROM t_basket WHERE userId = ? AND isDeleted=false ORDER BY createdAt DESC";
	    $data = $db->fetchAll($sql, array($userId));
	    return $data;
    }

    /** 我的菜篮数量 **/
    public static function countByUid($db, $userId) {
        $sql = "SELECT count(1) AS c FROM t_basket WHERE userId = ? AND isDeleted=false";
        $data = $db->fetchAssoc($sql, array($userId));
        return $data;
    }


    /**通过ID查找菜篮*/
    public static function getById($db, $id) {
        $sql = "SELECT * FROM t_basket WHERE id = ? AND isDeleted=false";
	    $data = $db->fetchAssoc($sql, array($id));
	    return $data;
    }

   	/** 更改菜篮isChekced */
    public static function check($db, $id, $isChecked) {
        $sql = "UPDATE t_basket SET isChecked=$isChecked WHERE id = ?";
	    $data = $db->executeUpdate($sql, array($id));
	    return $data;
    }

    /** 批量更改菜篮isChekced */
    public static function checkByTypeSid($db, $type, $sourceId, $checked) {
        $sql = "UPDATE t_basket SET isChecked=$checked WHERE type = ? AND sourceId=?";
	    $data = $db->executeUpdate($sql, array($type, $sourceId));
	    return $data;
    }

    /** 删除 */
    public static function deleteByTypeSid($db, $type, $sourceId) {
        $sql = "DELETE FROM t_basket WHERE type = ? AND sourceId=?";
	    $data = $db->executeUpdate($sql, array($type, $sourceId));
	    return $data;
    }

    /** 通过用户ID删除 */
    public static function deleteByUid($db, $userId) {
        $sql = "DELETE FROM t_basket WHERE userId = ?";
	    $data = $db->executeUpdate($sql, array($userId));
	    return $data;
    }
}

